﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace Common.Library.HTTP
{
    public class HttpClientBearerToken
    {
        static string authorization = Bearer();


        #region Get  请求
        /// <summary>
        /// Get  请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="timeOut">超时时间</param>
        /// <param name="outnum">一个阈值，如果超过这个值直接抛异常</param>
        /// <returns></returns>
        public static HttpResponseMessage Get(string url, int timeOut = 60, int outnum = 1)
        {
            HttpResponseMessage response = null;
            using (var http = new HttpClient())
            {
                http.Timeout = new TimeSpan(0, 0, timeOut);
                var message = new HttpRequestMessage(HttpMethod.Get, url);
                message.Headers.Add("Authorization", authorization);
                response = http.SendAsync(message).Result;
                //授权未通过  重新获取Token 继续发送请求
                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    if (outnum == 5)
                    {
                        throw new Exception("接口调用失败");
                    }
                    //重新获取Token信息
                    authorization = Bearer();
                    response = Get(url, timeOut, outnum++);
                }
                return response;
            }
        }
        #endregion

        #region Post请求
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="requestUrl">请求地址</param>
        /// <param name="content">请求上下文</param>
        /// <returns></returns>
        public static HttpResponseMessage Post(string requestUrl, HttpContent content, int timeOut = 60, int outnum = 5)
        {
            var response = new HttpResponseMessage();
            using (var http = new HttpClient())
            {
                http.Timeout = new TimeSpan(0, 0, timeOut);
                var message = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                message.Headers.Add("Authorization", authorization);
                message.Content = content;
                response = http.SendAsync(message).Result;

                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    if (outnum == 5)
                    {
                        throw new Exception("接口调用失败");
                    }
                    //重新获取Token信息
                    authorization = Bearer();
                    response = Post(requestUrl, content, timeOut, outnum++);
                }
                return response;
            }
        }


        #endregion


        private static string Bearer()
        {
            string token = "";
            string ChannelCoding = "test";
            string channelKey = "fe0faa57fd1cfd87";
            string signature = "";
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
            long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数
            signature = TO32MD5(channelKey + timeStamp).ToUpper();

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("ChannelCoding", ChannelCoding);
            dic.Add("TimeStamp", timeStamp.ToString());
            dic.Add("Signature", signature);
            FormUrlEncodedContent content = new FormUrlEncodedContent(dic);
            var res = HttpClientHelper.Post("http://10.7.19.39:8900/api/v1/Auth/Token", content);
            var json = res.Content.ReadAsStringAsync().Result;
            Res<TokenDto> dto = JsonConvert.DeserializeObject<Res<TokenDto>>(json);
            if (dto.code == 200)
            {
                return "Bearer " + dto.result.data; //
            }
            throw new Exception("错误");
        }

        public static string TO32MD5(string srcstr)
        {
            MD5 md5 = MD5.Create();
            string md5str = "";
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(srcstr));
            for (int i = 0; i < s.Length; i++)
            {
                string btos = s[i].ToString("X");
                if (btos.Length == 1)
                {
                    btos = "0" + btos;
                }
                md5str = md5str + btos;
            }
            return md5str;
        }
    }

    public class Res<T>
    {
        public int code { get; set; }
        public string msg { get; set; }
        public T result { get; set; }
    }

    public class TokenDto
    {
        public string data { get; set; }
        public int status { get; set; }
        public string message { get; set; }
    }


}
